﻿using ExcelUnity.Exporter;
using ExcelUnity.Exporter.Exporters;
using ExcelUnity.Exporter.Styles;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Drawing;
using System.Drawing.Text;

namespace ExcelUnity.WebTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly IExcelExporter _exporter;

        private readonly IWebHostEnvironment _webHostEnvironment;
        public TestController(IExcelExporter exporter, IWebHostEnvironment webHostEnvironment)
        {
            _exporter = exporter;
            _webHostEnvironment = webHostEnvironment;
        }

        [HttpGet]
        public IActionResult ExportWithWatermark()
        {
            using var fontCollection = new PrivateFontCollection();
            fontCollection.AddFontFile(Path.Combine(_webHostEnvironment.WebRootPath, "fonts", "simkai.ttf"));
            DataTable dt = new();
            dt.Columns.Add("RTime", typeof(string));
            dt.Columns.Add("Result", typeof(string));
            dt.Columns.Add("OName", typeof(string));
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["RTime"] = "RTime" + i;
                dr["OName"] = "OName" + i;
                dt.Rows.Add(dr);
            }
            var warterMarket = "技术部门";
            var sheet = new ExportSheet(dt)
            {
                Title = new ExportSheetTitle("用户列表")
                {
                    Style = new BaseStyle
                    {
                        IsBold = true,
                        HorizontalAlign = HorizontalAlign.Center
                    }
                },
                WaterMark = new ExportSheetWarterMark(warterMarket)
                {
                    Font = new Font(fontCollection.Families[0], 14),
                    Width = warterMarket.Length * 25,
                    Height = warterMarket.Length * 25
                }
            };
            var bookmodel = new ExportBook(sheet);

            using var outStream = new MemoryStream();
            _exporter.Export(bookmodel, outStream);
            return File(outStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx");
        }
    }
}
